package com.sync.hkmjsyncdata.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sync.hkmjsyncdata.pojo.po.AuthInfo;
import com.sync.hkmjsyncdata.pojo.po.HkPerson;
import com.sync.hkmjsyncdata.pojo.po.HkPoint;
import com.sync.hkmjsyncdata.pojo.po.HkRegion;
import com.sync.hkmjsyncdata.service.IAuthInfoService;
import com.sync.hkmjsyncdata.service.IHkPointService;
import com.sync.hkmjsyncdata.service.IHkRegionService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SendMjPoint {

    @Value("${gyhlw.host}")
    private String requestHost;

    @Resource
    IAuthInfoService authInfoService;

    @Resource
    IHkPointService hkPointService;


    /**
     * 发送门禁点位
     */
    @XxlJob("sendMjPoint")
    public void sendMjPointData() {
        XxlJobHelper.log("开始上传海康门禁点信息");
        AuthInfo authInfo = authInfoService.getById("1111");
        if (ObjectUtils.isEmpty(authInfo)) {
            XxlJobHelper.log("获取认证信息失败，取消删上传门禁点");
            return;
        }
        //上传新增数据
        sendData(authInfo.getToken(), 1,"新增");
        sendData(authInfo.getToken(), 2,"修改");
        sendData(authInfo.getToken(), 3,"删除");
    }

    private void sendData(String token, int opTyp, String sendType) {
        LambdaQueryWrapper<HkPoint> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HkPoint::getOpTyp, opTyp).last(" limit 999");
        List<HkPoint> addResult = hkPointService.list(queryWrapper);
        XxlJobHelper.log("开始推送{}数据,{}条", sendType, addResult.size());
        if (ObjectUtils.isEmpty(addResult)) {
            return;
        }
        JSONObject params = new JSONObject();
        params.put("dataList", addResult);
        MediaType mediaType = MediaType.parse("application/json");
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        RequestBody body = RequestBody.create(mediaType, params.toJSONString());
        Request request = new Request.Builder()
                .url(requestHost + "/api/access-control/deviceList")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", token)
                .build();
        try {
            Response response = client.newCall(request).execute();
            assert response.body() != null;
            String responseData = response.body().string();
            XxlJobHelper.log("推送结果:{}", responseData);


            if (ObjectUtils.isNotEmpty(responseData)) {
                JSONObject result = JSON.parseObject(responseData);
                if (result.getInteger("status") == 200) {
                    JSONObject data = result.getJSONObject("data");
                    List<String> ids = new ArrayList<>();
                    if (ObjectUtils.isNotEmpty(data)) {
                        JSONArray errorDatas = data.getJSONArray("errorData");
                        for (int i = 0; i < errorDatas.size(); i++) {
                            JSONObject item = errorDatas.getJSONObject(i);
                            if (item.getInteger("failTyp") != 1) {
                                ids.add(item.getString("mjdId"));
                            }
                        }
                    }
                    List<HkPoint> sucessPPoints = addResult.stream().filter(person -> !ids.contains(person.getMjdId())).toList();
                    if(opTyp==3){
                        hkPointService.removeBatchByIds(sucessPPoints.stream().map(HkPoint::getMjdId).toList());
                    }else {
                        sucessPPoints.forEach(point->point.setOpTyp(4));
                        hkPointService.updateBatchById(sucessPPoints);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
